package com.sobot.kb.sharding;

import java.util.Collection;

import com.sobot.kb.ResourceBundleUtils;

import io.shardingsphere.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

public class PreciseModuloTableShardingAlgorithm implements PreciseShardingAlgorithm<String> {

	private static final Integer DATABASES_COUNT = Integer
			.valueOf(ResourceBundleUtils.getStringProp("kb.datasource.databases.count"));

	@Override
	public String doSharding(final Collection<String> availableTargetNames,
			final PreciseShardingValue<String> shardingValue) {
		final int hashCode = Math.abs(shardingValue.getValue().hashCode());// companyId de 的绝对hash
		for (String each : availableTargetNames) {
			if (each.endsWith(hashCode % DATABASES_COUNT + "")) {
				System.out.println("companyId : " + shardingValue.getValue() + "=== hash abs :" + hashCode+",  databases ："+each);
				return each;
			}
		}
		throw new UnsupportedOperationException();
	}

}
